<?php
/** 用户添加地址 */
namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\validate\AddressNew;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\api\model\UserAddress;
use app\lib\SuccessMessage;
use app\lib\exception\UserException;

class Address extends BaseController{

    // 前置方法检测权限
    protected $beforeActionList=[
        'checkPrimaryScope'=>['only'=>'createOrUpdateAddress,getUserAddress']
    ];

    /**
     * 获取用户地址信息
     * @return UserAddress
     * @throws UserException
     */
    public function getUserAddress(){
        $uid = TokenService::getCurrentUid();
        $userAddress = UserAddress::where('user_id', $uid)
            ->find();
        if(!$userAddress){
            throw new UserException([
               'msg' => '用户地址不存在',
                'errorCode' => 60001
            ]);
        }
        return $userAddress;
    }
    
    /**
     * 更新或者创建用户收获地址
     */
    public function createOrUpdateAddress(){
        $validate=new AddressNew();
        $validate->goCheck();
        //根据Token获取uid
        //根据uid查找用户数据，判断用户是否存在，如果不存在抛出异常
        //获取用户从客户端提交的地址信息
        //根据用户地址信息是否存在，从而判断添加地址还是更新地址

        $uid=TokenService::getCurrentUid();
        $user=UserModel::get($uid);
        if(!$user){
            throw new UserException();
        }
        $dataArray=$validate->getDataByRule(input('post.'));
        
        $userAddress=$user->address;
        if(!$userAddress){
            $user->address()->save($dataArray);//创建
        }else{
            $user->address->save($dataArray);//更新
        }
        return json(new SuccessMessage(),201);
    }
}

